import React from "react";
import { useState, useRef, useEffect } from "react";
import { Comment } from "@ant-design/compatible";
import { Avatar, Tooltip, Button, message, List, Pagination, Input } from "antd";
import { LikeOutlined, DislikeOutlined, UserOutlined } from "@ant-design/icons";
import "@toast-ui/editor/dist/toastui-editor.css";
import { Editor } from "@toast-ui/react-editor";
import { useSelector, useDispatch } from "react-redux";
import { getIssueCommentById, addComment, getBookCommentById } from "@/api/comment";
import { getUserByIdApi, editUser } from "@/api/user";
import { formatDate } from "../../utils/tools";
import { updateIssue } from "@/api/issue";
import { updateBook } from "@/api/book";
import { updateUserInfoAsync } from "@/redux/userSlice";
export default function Discuss(props) {
  const editorRef = useRef();
  const dispatch = useDispatch();
  const { userInfo, isLogin } = useSelector((state) => state.user);
  const [commentList, setCommentList] = useState([]);
  const [bookValue, setBookValue] = useState("");
  const [pageInfo, setPageInfo] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [refresh, setRefresh] = useState(false); // 重新触发useEffect
  const [actionInfo, setActionInfo] = useState({
    likes: 0,
    dislikes: 0,
    action: null,
  });

  const actions = [
    <span>
      <Tooltip title="喜欢">
        <LikeOutlined />
      </Tooltip>
      <span style={{ paddingLeft: 8, cursor: "auto" }}>{actionInfo.likes}</span>
    </span>,
    <span>
      <Tooltip title="不喜欢">
        <DislikeOutlined />
      </Tooltip>
      <span style={{ paddingLeft: 8, cursor: "auto" }}>{actionInfo.dislikes}</span>
    </span>,
    <span>回复</span>,
  ];

  useEffect(() => {
    // 获得评论内容
    async function fetchCommentList() {
      let data = null;
      if (props.commentType === 1) {
        // 问题评论
        const res = await getIssueCommentById(props.targetId, {
          current: pageInfo.current,
          pageSize: pageInfo.pageSize,
        });
        data = res.data;
      } else if (props.commentType === 2) {
        // 书籍评论
        const res = await getBookCommentById(props.targetId, {
          current: pageInfo.current,
          pageSize: pageInfo.pageSize,
        });
        data = res.data;
      }

      for (let i = 0; i < data.data.length; i++) {
        const result = await getUserByIdApi(data.data[i].userId);
        // 将用户的信息添加到评论对象上面
        data.data[i].userInfo = result.data;
      }
      // 更新评论数据
      setCommentList(data.data);
      // 更新分页数据
      setPageInfo({
        current: data.currentPage,
        pageSize: data.eachPage,
        total: data.count,
      });
    }

    if (props.targetId) {
      fetchCommentList();
    }
  }, [props.targetId, refresh, pageInfo.current, pageInfo.pageSize]);

  // 添加评论
  const handleAddComment = () => {
    let content = null;
    if (!isLogin) {
      message.warning("请先登录，再进行评论");
    } else {
      if (props.commentType === 1) {
        content = editorRef.current.getInstance().getHTML();
      } else if (props.commentType === 2) {
        // 书籍评论的内容
        content = bookValue;
      }
      if (!content.trim() || !content.replace(/<[^>]*>/g, "").trim()) {
        message.error("内容不能为空");
        return;
      }
      // 提交评论
      addComment({
        userId: userInfo._id,
        bookId: props.bookInfo?._id,
        issueId: props.issueInfo?._id,
        typeId: props.issueInfo ? props.issueInfo.typeId : props.bookInfo.typeId,
        commentContent: content,
        commentType: props.commentType,
      });

      // 该条问答或者书籍的评论数量加一
      if (props.commentType === 1) {
        updateIssue(props.issueInfo._id, {
          commentNumber: ++props.issueInfo.commentNumber,
        });
        editUser(userInfo._id, {
          points: userInfo.points + 4,
        });
        dispatch(
          updateUserInfoAsync({
            userId: userInfo._id,
            newInfo: { points: userInfo.points + 4 },
          })
        );
        message.success("评论添加成功，积分+4");
        editorRef.current.getInstance().setHTML("");
      } else if (props.commentType === 2) {
        updateBook(props.bookInfo._id, {
          commentNumber: ++props.bookInfo.commentNumber,
        });
        editUser(userInfo._id, {
          points: userInfo.points + 2,
        });
        dispatch(
          updateUserInfoAsync({
            userId: userInfo._id,
            newInfo: { points: userInfo.points + 2 },
          })
        );
        message.success("评论添加成功，积分+2");
        setBookValue("");
      }
      setRefresh(!refresh);
    }
  };

  const handlePageChange = (current, pageSize) => {
    setPageInfo({
      current,
      pageSize,
    });
  };
  return (
    <>
      <Comment
        avatar={<Avatar src={userInfo?.avatar} size="default" icon={<UserOutlined />} />}
        content={
          <>
            {props.commentType === 1 ? (
              <Editor
                initialValue=""
                previewStyle="vertical"
                height="300px"
                initialEditType="WYSIWYG"
                useCommandShortcut={true}
                ref={editorRef}
              />
            ) : (
              <Input.TextArea
                value={bookValue}
                onChange={(e) => setBookValue(e.target.value)}
                style={{ width: "100%", height: "105px" }}
              />
            )}
            <Button
              type="primary"
              style={{ marginTop: "15px" }}
              disabled={!isLogin}
              onClick={handleAddComment}
            >
              提交评论
            </Button>
          </>
        }
      />

      {isLogin && commentList.length > 0 ? (
        <>
          <List
            header={<div>当前评论</div>}
            dataSource={commentList}
            renderItem={(item) => (
              <Comment
                actions={actions}
                author={<a>{item.userInfo.nickname}</a>}
                avatar={<Avatar src={item.userInfo.avatar} />}
                content={<div dangerouslySetInnerHTML={{ __html: item.commentContent }}></div>}
                datetime={
                  <Tooltip title={formatDate(item.commentDate, "year")}>
                    <span>{formatDate(item.commentDate, "year")}</span>
                  </Tooltip>
                }
              />
            )}
          />
          <div style={{ display: "flex", justifyContent: "center", margin: "40px 0" }}>
            <Pagination
              showQuickJumper
              defaultCurrent={1}
              {...pageInfo}
              onChange={handlePageChange}
            />
          </div>
        </>
      ) : isLogin && commentList.length === 0 ? (
        <p style={{ textAlign: "center", fontSize: "16px", marginBottom: "40px" }}>暂无评论</p>
      ) : (
        <p style={{ textAlign: "center", fontSize: "16px", marginBottom: "40px" }}>
          暂无权限查看，请登录再试
        </p>
      )}
    </>
  );
}
